<template>
  <div>
    <!--导航栏-->
    <van-nav-bar
      :left-text="getCurrentTime()"
      :title="getNewDate(this.date)"
      fixed
      placeholder
    />
    <!--显示农历-->
    <p class="time">{{ getFullYear() }} {{ getFullDate() }}</p>
    <div style="height: 22px"></div>

    <!--进度条说明-->
    <div class="jdt"></div>
    <a class="bfb">{{ date.getFullYear() }} 年已过去 {{ Progress }}%</a>
    <div style="height: 10px"></div>

    <!--进度条-->
    <div style="width: 70%; margin: 0 auto">
      <el-progress
        :text-inside="true"
        :stroke-width="18"
        :percentage="Progress"
      ></el-progress>
      <p style="font-size: 9px; text-align: right">
        {{ this.PastDays }}/{{ this.TotalDays }}
      </p>
    </div>
    <!--循环日期模块-->
    <div style="height: 40px;"></div><!--进度条下的留白-->
    <div :key="i" v-for="(item, i) in Festival">
      <div class="mk" :style="item.background" @click="bwl(i)" style="">
        <div>
          <div style="height: 18px; float: left; width: 95%; heigh: 10px"></div>
          <div
            style="float: right; color: white; width: 5%; heigh: 10px"
            @click="delect(item.id)"
            @click.stop="bwl"
          >
            ×&nbsp;&nbsp;
          </div>
        </div>
        <div>
          <div style="text-align: left; float: left">
            <a
              style="
                font-size: 20px;
                color: white;
                line-height: 2em;
                margin: 20px;
              "
              >{{ item.name }}</a
            ><br />
            <a
              style="
                font-size: 12px;
                color: #e7e7e7;
                line-height: 2em;
                margin: 20px;
              "
              >{{ item.date }}</a
            ><br />
            <a style="font-size: 12px; color: #e7e7e7; margin: 20px">{{
              item.full
            }}</a>
          </div>
          <div style="text-align: right; float: right">
            <a style="font-size: 12px; color: white">{{ item.str1 }}&nbsp;</a>
            <a style="font-size: 20px; color: white">{{ item.str2 }}&nbsp;</a>
            <a style="font-size: 12px; color: white"
              >{{ item.str3 }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a
            >
          </div>
        </div>
        <div style="height: 18px" @click="bwl(i)"></div>
      </div>
      <div style="height: 18px"></div>
    </div>

    <!--添加按钮，弹出弹框-->
    <el-button @click="drawer = true" type="primary" style="margin-left: 16px">
      添加纪念日
    </el-button>
    <!--弹框-->
    <el-dialog
      title="记录那些难忘的日子"
      :visible.sync="drawer"
      direction="btt"
    >
      <span>
        <el-input
          placeholder="请输入纪念日名称"
          v-model="iname"
          class="srk"
          clearable
          maxlength="10"
        >
        </el-input
        ><br /><br />
        <el-date-picker
          placeholder="请选择纪念日日期"
          v-model="idate"
          type="date" 
          class="srk"
          clearable
          value-format="yyyy-MM-dd"
        >
        </el-date-picker
        >
        <br /><br />
        <el-radio-group v-model="itypeRiLi">
          <el-radio label="农历" >农历</el-radio>
          <el-radio label="新历" >新历</el-radio>
        </el-radio-group>
        <br /><br />
        <el-input
          placeholder="请输入备忘内容（选填）"
          v-model="ibw"
          class="srk"
          clearable
        >
        </el-input
        ><br /><br />

        <el-radio-group v-model="itype">
          <el-radio label="1" >单次</el-radio>
          <el-radio label="2" >重复</el-radio>
        </el-radio-group>
        <br /><br />

        <a class="bfb">请选择背景:</a><br /><br />
        <div style="height: 520px;overflow: auto;">
          <div :key="i" v-for="(item, i) in imeg">

            <label>
              <input type="radio" v-model="whom" style="transform: translate(-42%, -350%);" :value="i"/>
              <img
              :src="item.url"
              alt=""
              style="width: 80%; height: 110px; max-width: 500px"
              @click="xz(i)"
            /><br />
            </label>
          </div>
        </div>
        <br />
        <br />
        <el-button type="primary" @click="add" :plain="true">确定</el-button><br /><br />

      </span>
    </el-dialog>
    <br /><br /><br /><br /><br /><br />
  </div>
</template>

<script>
import { getLunar } from "chinese-lunar-calendar";
import { NavBar } from "vant";
import calendarFormatter from '@/js/dateChange.js'
export default {
  //顶栏
  components: {
    [NavBar.name]: NavBar,
  },
  data() {
    return {
      uid: sessionStorage.getItem("uid"),
      date: new Date(), // 当前日期实例化
      Progress: 0, // 进度条
      PastDays: 0, // 过去的天数
      TotalDays: 0, // 所有天数
      iname: "", //自定义添加标题
      idate: "", //自定义时间
      ibc: "", //自定义添加背景
      ibw: "", //输入备忘内容
      itype: 0,
      istatus: 1,
      itypeRiLi:"",
      drawer: false,
      whom: [],
      // 暂时存放
      Analog: [],
      //存放自定义添加页的图片路径
      imeg: [
        {
          id: "0",
          url: require("../assets/custom/0.jpg"),
          urls: "../assets/custom/0.jpg"
        },
        {
          id: "1",
          url: require("../assets/custom/1.jpg"),
          urls: "../assets/custom/1.jpg"
        },
        {
          id: "2",
          url: require("../assets/custom/2.jpg"),
          urls: "../assets/custom/2.jpg"
        },
        {
          id: "3",
          url: require("../assets/custom/3.jpg"),
          urls: "../assets/custom/3.jpg"
        },
        {
          id: "4",
          url: require("../assets/custom/4.jpg"),
          urls: "../assets/custom/4.jpg"
        },
        {
          id: "5",
          url: require("../assets/custom/5.jpg"),
          urls: "../assets/custom/5.jpg"
        },
        {
          id: "6",
          url: require("../assets/custom/6.jpg"),
          urls: "../assets/custom/6.jpg"
        },
        {
          id: "7",
          url: require("../assets/custom/7.jpg"),
          urls: "../assets/custom/7.jpg"
        },
        {
          id: "8",
          url: require("../assets/custom/8.jpg"),
          urls: "../assets/custom/8.jpg"
        },
        {
          id: "9",
          url: require("../assets/custom/9.jpg"),
          urls: "../assets/custom/9.jpg"
        },
        {
          id: "10",
          url: require("../assets/custom/10.jpg"),
          urls: "../assets/custom/10.jpg"
        },
        {
          id: "11",
          url: require("../assets/custom/11.jpg"),
          urls: "../assets/custom/11.jpg"
        },{
          id: "12",
          url: require("../assets/custom/12.jpg"),
          urls: "../assets/custom/12.jpg"
        },
        {
          id: "13",
          url: require("../assets/custom/13.jpg"),
          urls: "../assets/custom/13.jpg"
        },{
          id: "14",
          url: require("../assets/custom/14.jpg"),
          urls: "../assets/custom/14.jpg"
        },{
          id: "15",
          url: require("../assets/custom/15.jpg"),
          urls: "../assets/custom/16.jpg"
        },
      ],
      Festival: [],
    };
  },
  created() {
    // 每0.1秒更新一次日期
    this.timer = setInterval(this.getTime, 100);
    this.getData();
  },
  methods: {
    // 获取数据
    getData(){
      this.$axios({
        url:"http://localhost/festival/cx/" + this.uid
      })
      .then((res)=>{
        const temp = [];
        // 遍历数据
        res.data.data.forEach(function(data) {
          data.backdrop = data.backdrop.match(/\d+/)[0];
          temp.push({
            id: data.id,
            uid: data.uid,
            name: data.name,
            date: data.date,
            bw: data.remarks,
            status: data.status,
            type: data.type,
            calendar:data.calendar,
            background: {
              // 背景图片地址
              //backgroundImage: "url(" + require(`${data.backdrop}`) + ")",
              backgroundImage: "url(" + require(`../assets/custom/${data.backdrop}.jpg`) + ")",
              // 背景图片大小
              backgroundSize: "cover",
            }
          });
        });
        this.Analog = temp;
      })
      .catch((err)=>{
        console.log(err);
      });
    },
    
    //当前日期
    getTime() {
      // 更新当前日期变量
      this.date = new Date();
      this.Progress = this.getProgress();
      this.Festival = this.getFestival();
    },

    // 获取农历年
    getFullYear(date = this.date) {
      return getLunar(date.getFullYear(), date.getMonth() + 1, date.getDate())
        .lunarYear;
    },

    // 获取农历日期
    getFullDate(date = this.date) {
      return getLunar(date.getFullYear(), date.getMonth() + 1, date.getDate())
        .dateStr;
    },

    // 获取新历日期
    getNewDate(date, year = 0) {
      return (
        (date.getFullYear() + year) +
        "-" +
        (date.getMonth() + 1) +
        "-" +
        date.getDate()
      );
    },

    // 左上角当前时间
    getCurrentTime() {
      const hm = this.date.getHours() >= 12 ? "PM" : "AM";
      return (
        this.date.getHours() +
        ":" +
        this.date.getMinutes() +
        ":" +
        this.date.getSeconds() +
        " " +
        hm
      );
    },

    // 计算开始日期和结束日期差几天
    getBeginTime(begin, end) {
      var day = parseInt((new Date(end).getTime() - new Date(begin).getTime())) / (24 * 60 * 60 * 1000 );
      return Math.floor(day);
    },

    // 进度
    getProgress() {
      // 取当前 年份 1月1日做开始日期， 当前日期作为结束日期
      this.PastDays = this.getBeginTime(
        this.date.getFullYear() + "-1-1",
        this.getNewDate(this.date)
      );
      // 获取当前年天数
      this.TotalDays = this.getBeginTime(
        this.date.getFullYear() + "-1-1",
        this.date.getFullYear() + 1 + "-1-1"
      );
      // 结果保留两位小数
      return parseInt((this.PastDays / this.TotalDays) * 100);
    },

    // 遍历纪念日
    getFestival() {
      const temp = [];
      this.Analog.forEach((item) => {
        if(item.calendar == "新历"){
        if(item.status == 1){
        // 传入当前日期， 第二个是节日日期， 节日日期 - 当前日期是负数是已过 N天，否则是还有N天
        const days = this.getBeginTime(this.getNewDate(new Date()), item.date);
        // 计算农历
        const full = this.getFullDate(new Date(item.date));
        var str1, str2, str3;
        if (days < 0 && item.type == 1) {
          str1 = "已过";
          str2 = -days;
          str3 = "天";
        }else if (days < 0 && item.type == 2) {
          str1 = "还有";
          str2 = -this.getBeginTime(this.getNewDate(this.date, 1), item.date)+days*2;
          str3 = "天";
        } else if (days == 0) {
          str1 = "正是";
          str2 = "今天";
        } else {
          str1 = "还有";
          str2 = days;
          str3 = "天";
        }
        const strs = {
          id: item.id,
          name: item.name,
          date: item.date,
          bw: item.bw,
          days: days,
          full: full,
          str1: str1,
          str2: str2,
          str3: str3,
          background: item.background,
          time: item.date,
        };
        temp.push(strs);
      }
    }else{
      if(item.status == 1){
        // 传入当前日期， 第二个是节日日期， 节日日期 - 当前日期是负数是已过 N天，否则是还有N天
        var str = item.date
        var date1 = this.toDate(parseInt(str.substring(0,4)),parseInt(str.substring(5,7)),parseInt(str.substring(8,10)))
        const days1 = this.getBeginTime(this.getNewDate(new Date()), date1);
        // 计算农历
        const full = this.getFullDate(new Date(date1));
        var str12, str22, str32;
        if (days1 < 0 && item.type == 1) {
          str12 = "已过";
          str22 = -days1;
          str32 = "天";
        }else if (days1 < 0 && item.type == 2) {
          str12 = "还有";
          str22 = -this.getBeginTime(this.getNewDate(this.date, 1), item.date)+days1*2-3;
          str32 = "天";
        } else if (days1 == 0) {
          str12 = "正是";
          str22 = "今天";
          str32 = ""
        } else {
          str12 = "还有";
          str22 = days1;
          str32 = "天";
        }

        const strs1 = {
          id: item.id,
          name: item.name+"(农历)",
          date: date1,
          bw: item.bw,
          days: days1,
          full: full,
          str1: str12,
          str2: str22,
          str3: str32,
          background: item.background,
          time: item.date,
        };
        temp.push(strs1);
      }

    }
      });
      return temp;
    },

    //删除数据，从而删除div
    delect(i) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            url:"http://localhost/festival/"+i,
            method:"get",
            data:{
            },
          })
          .then((res)=>{
            this.$axios({
            url:"http://localhost/festival",
            method:"put",
            data:{
              id: res.data.data.id,
              uid: res.data.data.uid,
              name:res.data.data.name,
              date:res.data.data.date,
              backdrop:res.data.data.backdrop,
              remarks:res.data.data.remarks,
              type:res.data.data.type,
              calendar:res.data.data.calendar,
              status: 0,
            },
            }).then((res)=>{this.getData();})
            
          })
          .catch((err)=>{
            console.log(err);
          });
          this.$message({
            showClose: true,
            type: "success",
            message: "删除成功!",
          });
          
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "已取消删除",
          });
        });
        
    },

    //关闭弹框
    handleClose(done) {

      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    //点击出现备忘录提示
    bwl(i) {
      if (i >= 0 && this.Festival[i].bw != "") {
        this.$message({
          showClose: true,
          type: "success",
          message: this.Festival[i].bw,
          center: true,
        });
      } else if (i >= 0 && this.Festival[i].bw == "") {
        this.$message({
          showClose: true,
          message: "未添加备忘内容",
          center: true,
        });
      }
    },

    //添加页背景选择
    xz(i) {
      this.ibc = this.imeg[i].urls;
      console.log(this.ibc);
      this.$message({
        showClose: true,
        type: "success",
        message: "选择成功!",
      });
    },
    toDate( year, month, day){
      let to = calendarFormatter.lunar2solar( year, month, day);
      return to.cYear + "-" + to.cMonth + "-" + to.cDay;
    },

    //自定义添加纪念日
    add() {
      if (this.iname != "" && this.idate != "" && this.ibc != "") {
        const params = {
          uid: this.uid,
          name: this.iname,
          date: this.idate,
          remarks: this.ibw,
          backdrop: this.ibc,
          status: this.istatus,
          type: this.itype,
          calendar:this.itypeRiLi,
        };
        console.log(params)
        console.log(params);
        //清空输入框
        this.iname = "";
        this.idate = "";
        this.ibc = "";
        this.ibw = "";

        this.$axios({
          url:"http://localhost/festival/",
          method:"post",
          data:params,
        })
        .then((res)=>{
          //添加成功提示
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success",
          });
          this.getData();
        })
        .catch((err)=>{
          console.log(err);
        });
      } else if (this.iname != "" && this.idate != "" && this.ibc == "") {
        this.$message({
          showClose: true,
          message: "请选择背景",
          type: "warning",
        });
      } else {
        //添加失败
        this.$message.error({
          showClose: true,
          message: "添加失败，请完整输入",
        });
      }
      //关闭弹窗
      this.drawer = false;
    },
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除定时器
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.jdt {
  width: 70%;
  margin: 0 auto;
}
.bfb {
  color: #287553;
  font-size: 20px;
}
.time {
  font-size: 11px;
}
.mk {
  width: 80%;
  margin: 0px auto;
  border-radius: 10px;
  height: 110px;
}
.srk {
  width: 80%;
  max-width: 500px;
}
.el-popover {
  height: 500px;
  overflow: auto;
}
</style>

